<script setup lang="ts">
import type { realName } from '#/api/lesson/index';
import { computed, ref, onDeactivated, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { useAccessStore, useUserStore } from '@vben/stores';
import { ElMessage, ElMessageBox, ElSkeleton, ElSkeletonItem } from 'element-plus';
import { getCheckWhiteApi } from '#/api/certificate/white-link';
import { realNameAuthApi } from '#/api/lesson/index';
import { getCourseInfoByCertIdApi } from '#/api/manage/course'
import setPublicCode from '#/utils/setPublicKey';
import RealNameAuth from './modules/real-name-auth.vue';
import MarkdownViewer from '#/components/MarkdownViewer.vue';
import type { CourseItem } from '#/views/course/modules/course-mgr/types';
import { getImgUrl } from "#/utils/getImgUrl"
import { $t } from '@vben/locales'

defineOptions({ name: 'Home' });
const accessStore = useAccessStore();
const userStore = useUserStore();
const activeTab = ref('CourseMate')
const realNameDialog = ref(false);
const router = useRouter();
const route = useRoute();
const isQuick = ref(false);
const authRef = ref();
const authAlert = ref(false);
const alertTitle = ref('');
let timeout: number | any;
const submitLoading = ref(false);
const butName = computed(() => (isQuick.value ? '查看课程' : '报名学习'));
const courseTitle = ref('')
const courseDescription = ref('')
const courseImage = ref('')
const courseInfoEntity = ref<any>({})
const loading = ref(true)
const handleClose = () => {
  realNameDialog.value = false;
  close();
};

const introduction = ref('')
const highlights = ref('')

if (accessStore.accessToken && route.query.certifiedId) {
  // 目前定义为certifiedId：
  getCheckWhiteApi({ certifiedId: route.query.certifiedId as string }).then((res) => {
    isQuick.value = res.checked;
  });
} else if (accessStore.accessToken && route.query.courseId) {
  isQuick.value = true;
}

// 报名学习，只有报名成功了才能直接去到课程学习
const handleEnroll = () => {
  // realNameDialog.value = true;
  // return
  // return router.push('/lesson/learn');
  // 未登录
  if (!accessStore.accessToken) {
    ElMessageBox.confirm('请先登录', '提示', {
      confirmButtonText: '去登录',
      type: 'warning'
    }).then(() => {
      router.push({ path: '/auth/login' });
    })
    return
  }
  // 实名验证
  if (!userStore.userInfo?.isRealName) {
    realNameDialog.value = true;
    return
  }
  // 没有白名单
  if (!isQuick.value) {
    ElMessageBox.confirm(
      '请联系工作人员兑换专项认证，兑换后方可进行查看课程。',
      '提示',
      {
        confirmButtonText: '确定',
        type: 'warning',
      },
    );
  } else {
    router.push('/lesson/learn/' + courseInfoEntity.value.id);
  }
};
const submit = () => {
  alertTitle.value = '';
  authAlert.value = false;
  authRef.value.getData().then((res: realName) => {
    if (!res) return;
    const data = { ...res };
    data.idCard = setPublicCode(res.idCard ?? '') || '';
    realNameAuthApi(data)
      .then(() => {
        ElMessage.success('认证成功');
        realNameDialog.value = false;
        timeout = setTimeout(() => {
          window.location.reload();
        }, 1500)
      })
      .catch((error) => {
        console.log(error, 'err');
        alertTitle.value = error.message || '';
        authAlert.value = true;
      });
  });
};
const getCourseInfo = async () => {
  try {
    loading.value = true
    // 优先使用 certificateId，如果没有则使用 courseId
    const certificateId = route.query.certifiedId as string;
    const courseId = route.query.courseId as string;

    const params: any = {};
    if (certificateId) {
      params.certificateId = certificateId;
    } else if (courseId) {
      params.courseId = courseId;
    }

    const res = await getCourseInfoByCertIdApi(params)
    const courseInfo: CourseItem = res || {}
    courseInfoEntity.value = courseInfo
    introduction.value = courseInfo.introduction || ''
    highlights.value = courseInfo.highlights || ''
    courseTitle.value = courseInfo.name || ''
    courseDescription.value = courseInfo.summary || ''

    if (courseInfo?.icon) {
      // 如果有图标路径，从 OBS 加载图片
      try {
        const imgData = await getImgUrl(courseInfo.icon)
        if (imgData instanceof ArrayBuffer) {
          // 将二进制数据转换为 Blob
          const blob = new Blob([imgData], { type: 'image/png' })
          courseImage.value = URL.createObjectURL(blob)
        }
      } catch (err) {
        console.error($t('courseMgr.loadImageFail'), err)
        ElMessage.error($t('courseMgr.loadImageFail'))
      }
    }
  } finally {
    loading.value = false
  }
}
const close = () => {
  authAlert.value = false;
};
onMounted(() => {
  getCourseInfo()
})
onDeactivated(() => {
  timeout && clearInterval(timeout)
})
</script>
<template>
  <div class="h-full w-[100%] overflow-hidden flex flex-col bg-[#f4f5f5]">
    <!-- 顶部内容 -->
    <div class="container mb-8 flex flex-col items-center bg-[#fff] p-[30px] md:flex-row md:items-start">
      <!-- 加载时显示骨架屏 -->
      <ElSkeleton v-if="loading" :loading="loading" animated>
        <template #template>
          <div class="flex flex-col items-center md:flex-row md:items-start w-full">
            <!-- 课程图片骨架 -->
            <ElSkeletonItem variant="image"
              style="width: 320px; height: 180px; margin-bottom: 16px; margin-right: 32px;" />
            <!-- 课程信息骨架 -->
            <div class="flex-1 pt-0">
              <!-- 标题骨架 -->
              <ElSkeletonItem variant="h1" style="width: 60%; height: 32px; margin-bottom: 8px;" />
              <!-- 描述骨架 -->
              <div class="mb-4 pb-12">
                <ElSkeletonItem variant="text" style="width: 90%; height: 20px; margin-bottom: 8px;" />
                <ElSkeletonItem variant="text" style="width: 85%; height: 20px; margin-bottom: 8px;" />
                <ElSkeletonItem variant="text" style="width: 70%; height: 20px;" />
              </div>
              <!-- 按钮骨架 -->
              <ElSkeletonItem variant="button" style="width: 100px; height: 32px;" />
            </div>
          </div>
        </template>
      </ElSkeleton>

      <!-- 加载完成后显示实际内容 -->
      <template v-else>
        <img :src="courseImage" class="mb-4 w-[320px] h-[180px] md:mb-0 md:mr-8" />
        <div class="pt-[0px]">
          <h2 class="mb-2 text-2xl font-bold">{{ courseTitle }}</h2>
          <p class="mb-4 pb-[50px] text-gray-600 text-[14px] leading-[20px]">{{ courseDescription }}</p>
          <el-button @click="handleEnroll" type="primary" plain>
            {{ butName }}
          </el-button>
        </div>
      </template>
    </div>

    <!-- 课程信息 -->
    <div class="container bg-[#fff] pt-[20px] flex-1 min-h-[1px] overflow-hidden">
      <!-- 加载时显示 tabs 骨架屏 -->
      <ElSkeleton v-if="loading" :loading="loading" animated>
        <template #template>
          <div class="px-4 pb-4">
            <!-- Tab 标签骨架 -->
            <div class="flex border-b border-gray-200 mb-4">
              <ElSkeletonItem variant="text"
                style="width: 80px; height: 24px; margin-right: 32px; margin-bottom: 12px;" />
              <ElSkeletonItem variant="text" style="width: 80px; height: 24px; margin-bottom: 12px;" />
            </div>
            <!-- Tab 内容骨架 -->
            <div class="p-2 h-72">
              <ElSkeletonItem variant="text" style="width: 95%; height: 20px; margin-bottom: 12px;" />
              <ElSkeletonItem variant="text" style="width: 90%; height: 20px; margin-bottom: 12px;" />
              <ElSkeletonItem variant="text" style="width: 85%; height: 20px; margin-bottom: 12px;" />
              <ElSkeletonItem variant="text" style="width: 92%; height: 20px; margin-bottom: 12px;" />
              <ElSkeletonItem variant="text" style="width: 88%; height: 20px; margin-bottom: 12px;" />
              <ElSkeletonItem variant="text" style="width: 75%; height: 20px;" />
            </div>
          </div>
        </template>
      </ElSkeleton>

      <!-- 加载完成后显示实际 tabs -->
      <el-tabs v-else v-model="activeTab">
        <el-tab-pane label="课程信息" name="CourseMate">
          <div class="p-[10px] text-[16px] h-full overflow-auto">
            <MarkdownViewer :content="introduction" />
          </div>
        </el-tab-pane>
        <el-tab-pane label="课程亮点" name="SkillForge">
          <div class="pt-[10px] text-[16px] h-full overflow-auto">
            <MarkdownViewer :content="highlights" />
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <!-- 实名认证 -->
    <el-dialog v-model="realNameDialog" :destroy-on-close="true" title="实名认证" width="500" :append-to-body="true"
      :close-on-click-modal="false" :before-close="handleClose">
      <!-- 认证异常 -->
      <el-alert v-if="authAlert" :title="alertTitle" type="error" @close="close" />
      <RealNameAuth ref="authRef" class="container pb-[30px] pl-[60px] pr-[60px] pt-[30px]" />
      <template #footer>
        <div class="dialog-footer text-center">
          <el-button @click="realNameDialog = false" class="w-[90px]">
            取消
          </el-button>
          <el-button type="primary" @click="submit" class="w-[90px]" v-loading="submitLoading">
            确 认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<style scoped>
ul,
li {
  list-style: none;
}

.circular {
  animation: loading-rotate 2s linear infinite;
}

/* 骨架屏样式优化 */
:deep(.el-skeleton__item) {
  background: linear-gradient(90deg, #f2f2f2 25%, #e6e6e6 50%, #f2f2f2 75%);
  background-size: 400% 100%;
  animation: skeleton-loading 1.4s ease infinite;
}

@keyframes skeleton-loading {
  0% {
    background-position: 100% 50%;
  }

  100% {
    background-position: -100% 50%;
  }
}

/* 响应式优化 */
@media (max-width: 768px) {
  :deep(.el-skeleton__item) {
    margin-bottom: 8px;
  }
}
.el-tabs {
  height: 100%;
  :deep(.el-tabs__content) {
    flex: 1;
    min-height: 1px;
    overflow: auto;
  }
}
</style>
